{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "实例：对一系列文本行做遍历文本匹配操作，每当发现有匹配时就输出当前的匹配行以及最后检查过的N行文本\n",
    "<br>\n",
    "解决：使用固定长度的deque实现。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true,
    "jupyter": {
     "outputs_hidden": true
    }
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "this line4 before py1 .....\n",
      "this line5 before py1 .....\n",
      "this line6 before py1 .....\n",
      "this line7 before py1 .....\n",
      "this line8 before py1 .....\n",
      "key word python1\n",
      "--------------------\n",
      "this line1 before py2 .....\n",
      "this line2 before py2 .....\n",
      "this line3 before py2 .....\n",
      "this line4 before py2 .....\n",
      "this line5 before py2 .....\n",
      "key word python2\n",
      "--------------------\n",
      "this line3 before py3 .....\n",
      "this line4 before py3 .....\n",
      "this line5 before py3 .....\n",
      "this line6 before py3 .....\n",
      "this line7 before py3 .....\n",
      "key word python3\n",
      "--------------------\n"
     ]
    }
   ],
   "source": [
    "from collections import deque\n",
    "\n",
    "def search(lines, pattern, history=5):\n",
    "    previous_lines = deque(maxlen=history)\n",
    "    for line in lines:\n",
    "        if pattern in line:\n",
    "            yield line, previous_lines\n",
    "        previous_lines.append(line)\n",
    "\n",
    "with open('somefile.txt') as f:\n",
    "    for line, prevlines in search(f, 'python', 5):\n",
    "        for pline in prevlines:\n",
    "            print(pline, end='')\n",
    "        print(line, end='')\n",
    "        print('-'*20)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3.7.4 64-bit",
   "language": "python",
   "name": "python37464bit0eab7a6caf29454899b876d50238c56e"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
